class ProjectWebsController < ApplicationController
  before_action :set_project, except: []

  def show
    @panel_heading = "#{@project.name} | WEB测试页面"
    @extra = JSON.pretty_generate (JSON.parse(rds[:extra]).presence || DEFAULT_EXTRA  rescue DEFAULT_EXTRA)
    @rds = rds
  end

  DEFAULT_EXTRA = {"customer" => {}}

  def set_settings
    params[:subdomain].present? && rds[:subdomain] = params[:subdomain]
    params[:im_user_key].present? && rds[:im_user_key] = params[:im_user_key]
    params[:im_web_plugin_id].present? && rds[:im_web_plugin_id] = params[:im_web_plugin_id]
    params[:web_token].present? && rds[:web_token] = params[:web_token]
    
    extra = (JSON.parse(params[:extra]) rescue DEFAULT_EXTRA)
    extra.is_a?(String) && extra = (JSON.parse(extra) rescue DEFAULT_EXTRA)
    Rails.logger.info "extra1: #{extra.inspect}"

    extra.present? && extra.is_a?(Hash) && rds[:extra] = extra.to_json

    @extra = JSON.pretty_generate rds[:extra]

    rds[:web_plugin_code] = get_web_plugin_code(extra)
    @rds = rds
    redirect_to project_web_path(@project)
  end

  def refresh_code
    extra = JSON.parse rds[:extra]
    rds[:web_plugin_code] = get_web_plugin_code(extra)
    @rds = rds
    redirect_to project_web_path(@project)
  end

private

  def web_sign!(p = {})
    sign_str = p.slice(:nonce, :timestamp, :web_token).map{|k,v| "#{k}=#{v}"}.sort.join("&")
    sign_str = "#{sign_str}&#{rds[:im_user_key]}"
    signature = Digest::SHA1.hexdigest(sign_str).upcase
  end

  def get_web_plugin_code(extra)
    time = Time.now
    Rails.logger.info "extra: #{extra.inspect}"
    customer = extra.delete('customer')
    inputs = {
      "code" => "aajd",
      "link" => "//#{rds[:subdomain]}/im_client?web_plugin_id=#{rds[:im_web_plugin_id]}",
    }.merge(extra)

    inputs[:customer] = customer || {}
    inputs[:customer].merge!(
    {
        nonce: time.to_i,
        timestamp: time.to_i * 1000,
        web_token: rds[:web_token],
     }
   )

    inputs[:customer][:signature] = web_sign!(inputs[:customer])

    resp = %Q{
(function(a,h,c,b,f,g){
  a["UdeskApiObject"]=f;
  a[f]=a[f]||function(){(a[f].d=a[f].d||[]).push(arguments)};
  g=h.createElement(c);g.async=1;g.src=b;c=h.getElementsByTagName(c)[0];
  c.parentNode.insertBefore(g,c)})(window,document,"script","//#{rds[:subdomain]}/im_client/js/udeskApi.js","ud");
ud(
    #{JSON.pretty_generate inputs}
  );
}
  end

  def set_project
      @project = current_user.projects.find(params[:id])
  end

  def rds
    return @test_redis if @test_redis
    namespace = "web:#{@project.id}"
    @test_redis = Redis::Namespace.new(namespace, :redis=> $redis)
  end

end
